<?php
declare (strict_types=1);

namespace app\admin\logic\system;

use app\admin\model\system\Message as MessageModel;
use app\common\exception\LogicException;
use think\facade\Db;

/**
 * 系统消息
 */
class Message
{

    /**
     * 发送消息
     * Author   Martinsun<syh@sunyonghong.com>
     * Date 2020-06-23
     *
     * @param string $key   [description]
     * @param array  $value [description]
     */
    public static function send(string $title, string $content, int $admin_user_id, string $message_type = null)
    {
        $message                = new MessageModel();
        $message->title         = $title;
        $message->content       = $content;
        $message->admin_user_id = $admin_user_id;
        $message->message_type  = $message_type;

        if (!$message->save()) {
            throw new LogicException("发送失败");
        }
    }

    /**
     * 消息列表
     * Author   Martinsun<syh@sunyonghong.com>
     * Date 2020-06-23
     *
     * @return   [type]                         [description]
     */
    public function getList()
    {
        $model    = new MessageModel();
        $pageSize = $model->getListRows();

        return $model->order('create_time', 'DESC')->paginate($pageSize);
    }

    /**
     * 设置已读状态
     * Author   Martinsun<syh@sunyonghong.com>
     * Date 2020-08-11
     *
     * @param int $message_id    [description]
     * @param int $admin_user_id [description]
     */
    public function setRead(int $message_id, int $admin_user_id)
    {
        $res = MessageModel::update(['is_read' => 1], ['id' => $message_id, 'admin_user_id' => $admin_user_id]);

        if (!$res) {
            throw new LogicException("设置已读状态失败");

        }

        return $this->getNoReadCount($admin_user_id);
    }

    /**
     * 获取未读的消息数量
     * Author   Martinsun<syh@sunyonghong.com>
     * Date 2020-08-11
     *
     * @param int $admin_user_id [description]
     * @return   [type]                                        [description]
     */
    public function getNoReadCount(int $admin_user_id)
    {
        return MessageModel::where('admin_user_id', $admin_user_id)->where('is_read', 0)->count();
    }

    /**
     * 设置消息全部已读
     * Author: 亓官雨树 <lucky.max@foxmail.com>
     * Date: 22/02/08
     *
     * @param int $admin_user_id
     * @return mixed
     */
    public function setReadAll(int $admin_user_id): void
    {
        $res = Db::name('system_message')->where(['admin_user_id' => $admin_user_id])->update(['is_read' => 1]);

        if (false === $res) {
            throw new LogicException("设置全部已读状态失败");
        }
    }
}
